﻿Imports System.Windows.Forms
Imports System.Globalization
Imports System.Threading
Imports System.Data.Sql
Imports System.ComponentModel
Imports System.Drawing
Imports System.Security.Permissions
Imports System.Text
Imports System.Data.SqlClient
Imports System.Data.OleDb
Imports System.Data.Odbc

Public Class SQLConnectionDialog
    Inherits Form
    Implements IDataConnectionUIControl
    ' Methods
    Public Sub New()
        MyBase.New()
        Me.InitializeComponent()
        Me.RightToLeft = RightToLeft.Inherit
        Dim preferredCheckBoxHeight As Integer = LayoutUtils.GetPreferredCheckBoxHeight(Me.savePasswordCheckBox)
        If (Me.savePasswordCheckBox.Height < preferredCheckBoxHeight) Then
            Me.savePasswordCheckBox.Anchor = (AnchorStyles.Left Or (AnchorStyles.Bottom Or AnchorStyles.Top))
            'Me.loginTableLayoutPanel.Height = (Me.loginTableLayoutPanel.Height + Me.loginTableLayoutPanel.Margin.Bottom)
            'Me.loginTableLayoutPanel.Margin = New Padding(Me.loginTableLayoutPanel.Margin.Left, Me.loginTableLayoutPanel.Margin.Top, Me.loginTableLayoutPanel.Margin.Right, 0)
        End If
        Me.selectDatabaseComboBox.AccessibleName = TextWithoutMnemonics(Me.selectDatabaseRadioButton.Text)
        Me.attachDatabaseTextBox.AccessibleName = TextWithoutMnemonics(Me.attachDatabaseRadioButton.Text)
        Me._uiThread = Thread.CurrentThread
        'Initalize the Properties Controls
        Initialize(New SqlConnectionProperties())

        LoadProperties()
        SetAuthenticationOption(Me, Nothing)
        SetDatabaseOption(Me, Nothing)
        Me.ShowInTaskbar = False
    End Sub

    Public Sub New(ByVal ConnectionString As String)
        Me.New()
        Dim I As New SqlConnectionProperties
        I.ConnectionStringBuilder.ConnectionString = ConnectionString
        Initialize(I)
        LoadProperties()
    End Sub

    Private Sub Browse(ByVal sender As Object, ByVal e As EventArgs) Handles browseButton.Click
        Dim component As New OpenFileDialog
        component.Title = My.Resources.SqlConnectionUIControl_BrowseFileTitle
        component.Multiselect = False
        component.RestoreDirectory = True
        component.Filter = My.Resources.SqlConnectionUIControl_BrowseFileFilter
        component.DefaultExt = My.Resources.SqlConnectionUIControl_BrowseFileDefaultExt
        If (Not MyBase.Container Is Nothing) Then
            MyBase.Container.Add(component)
        End If
        Try
            If (component.ShowDialog(MyBase.ParentForm) = DialogResult.OK) Then
                Me.attachDatabaseTextBox.Text = component.FileName.Trim
            End If
        Finally
            If (Not MyBase.Container Is Nothing) Then
                MyBase.Container.Remove(component)
            End If
            component.Dispose()
        End Try
    End Sub

    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        If (disposing AndAlso (Not Me.components Is Nothing)) Then
            Me.components.Dispose()
        End If
        MyBase.Dispose(disposing)
    End Sub

    Private Sub EnumerateDatabases()
        Dim table As DataTable = Nothing
        Dim basicConnection As IDbConnection = Nothing
        Dim reader As IDataReader = Nothing
        Try
            basicConnection = Me.Properties.GetBasicConnection
            Dim command As IDbCommand = basicConnection.CreateCommand
            command.CommandText = "SELECT CASE WHEN SERVERPROPERTY(N'EDITION') = 'SQL Data Services' OR SERVERPROPERTY(N'EDITION') = 'SQL Azure' THEN 1 ELSE 0 END"
            basicConnection.Open()
            If (CInt(command.ExecuteScalar) = 1) Then
                command.CommandText = "SELECT name FROM master.dbo.sysdatabases ORDER BY name"
            Else
                command.CommandText = "SELECT name FROM master.dbo.sysdatabases WHERE HAS_DBACCESS(name) = 1 ORDER BY name"
            End If
            reader = command.ExecuteReader
            table = New DataTable
            table.Locale = CultureInfo.CurrentCulture
            table.Load(reader)
        Catch obj1 As Exception
            table = New DataTable
            table.Locale = CultureInfo.InvariantCulture
        Finally
            If (Not reader Is Nothing) Then
                reader.Dispose()
            End If
            If (Not basicConnection Is Nothing) Then
                basicConnection.Dispose()
            End If
        End Try
        Me._databases = New Object(table.Rows.Count - 1) {}
        Dim i As Integer
        For i = 0 To Me._databases.Length - 1
            Me._databases(i) = table.Rows.Item(i).Item("name")
        Next i
        If (Thread.CurrentThread Is Me._uiThread) Then
            Me.PopulateDatabaseComboBox()
        ElseIf MyBase.IsHandleCreated Then
            MyBase.BeginInvoke(New ThreadStart(AddressOf Me.PopulateDatabaseComboBox))
        End If
    End Sub

    Private Sub EnumerateDatabases(ByVal sender As Object, ByVal e As EventArgs) Handles selectDatabaseComboBox.DropDown
        If (Me.selectDatabaseComboBox.Items.Count = 0) Then
            Dim current As Cursor = Cursor.Current
            Cursor.Current = Cursors.WaitCursor
            Try
                If ((Me._databaseEnumerationThread Is Nothing) OrElse (Me._databaseEnumerationThread.ThreadState = ThreadState.Stopped)) Then
                    Me.EnumerateDatabases()
                ElseIf (Me._databaseEnumerationThread.ThreadState = System.Diagnostics.ThreadState.Running) Then
                    Me._databaseEnumerationThread.Join()
                    Me.PopulateDatabaseComboBox()
                End If
            Finally
                Cursor.Current = current
            End Try
        End If
    End Sub

    Private Sub EnumerateServers()
        Dim dataSources As DataTable = Nothing
        Try
            dataSources = SqlDataSourceEnumerator.Instance.GetDataSources
        Catch obj1 As Exception
            dataSources = New DataTable
            dataSources.Locale = CultureInfo.InvariantCulture
        End Try
        Me._servers = New Object(dataSources.Rows.Count - 1) {}
        Dim i As Integer
        For i = 0 To Me._servers.Length - 1
            Dim str As String = dataSources.Rows.Item(i).Item("ServerName").ToString
            Dim str2 As String = dataSources.Rows.Item(i).Item("InstanceName").ToString
            If (str2.Length = 0) Then
                Me._servers(i) = str
            Else
                Me._servers(i) = (str & "\" & str2)
            End If
        Next i
        Array.Sort(Of Object)(Me._servers)
        If (Thread.CurrentThread Is Me._uiThread) Then
            Me.PopulateServerComboBox()
        ElseIf MyBase.IsHandleCreated Then
            MyBase.BeginInvoke(New ThreadStart(AddressOf Me.PopulateServerComboBox))
        End If
    End Sub

    Private Sub EnumerateServers(ByVal sender As Object, ByVal e As EventArgs) Handles serverComboBox.DropDown
        If (Me.serverComboBox.Items.Count = 0) Then
            Dim current As Cursor = Cursor.Current
            Cursor.Current = Cursors.WaitCursor
            Try
                If ((Me._serverEnumerationThread Is Nothing) OrElse (Me._serverEnumerationThread.ThreadState = ThreadState.Stopped)) Then
                    Me.EnumerateServers()
                ElseIf (Me._serverEnumerationThread.ThreadState = System.Diagnostics.ThreadState.Running) Then
                    Me._serverEnumerationThread.Join()
                    Me.PopulateServerComboBox()
                End If
            Finally
                Cursor.Current = current
            End Try
        End If
    End Sub

    Private Sub HandleComboBoxDownKey(ByVal sender As Object, ByVal e As KeyEventArgs) Handles selectDatabaseComboBox.KeyDown, serverComboBox.KeyDown
        If (e.KeyCode = Keys.Down) Then
            If (sender Is Me.serverComboBox) Then
                Me.EnumerateServers(sender, e)
            End If
            If (sender Is Me.selectDatabaseComboBox) Then
                Me.EnumerateDatabases(sender, e)
            End If
        End If
    End Sub

    Friend Sub Initialize(ByVal connectionProperties As IDataConnectionProperties) Implements IDataConnectionUIControl.Initialize
        If (connectionProperties Is Nothing) Then
            Throw New ArgumentNullException("connectionProperties")
        End If
        If (Not TypeOf connectionProperties Is SqlConnectionProperties AndAlso Not TypeOf connectionProperties Is OleDBSqlConnectionProperties) Then
            Throw New ArgumentException(My.Resources.SqlConnectionUIControl_InvalidConnectionProperties) 'SR.GetString("SqlConnectionUIControl_InvalidConnectionProperties"))
        End If
        If TypeOf connectionProperties Is OleDBSqlConnectionProperties Then
            Me.currentOleDBProvider = TryCast(connectionProperties.Item("Provider"), String)
        End If
        If TypeOf connectionProperties Is OdbcConnectionProperties Then
            Me.savePasswordCheckBox.Enabled = False
        End If
        Me._controlProperties = New ControlProperties(connectionProperties)
    End Sub

    'Private _manager As New ComponentResourceManager(GetType(SQLConnectionDialog))

    Private Sub InitializeComponent()
        Me.serverLabel = New System.Windows.Forms.Label()
        Me.serverTableLayoutPanel = New System.Windows.Forms.TableLayoutPanel()
        Me.serverComboBox = New System.Windows.Forms.ComboBox()
        Me.refreshButton = New System.Windows.Forms.Button()
        Me.logonGroupBox = New System.Windows.Forms.GroupBox()
        Me.LoginPanel = New System.Windows.Forms.Panel()
        Me.userNameLabel = New System.Windows.Forms.Label()
        Me.userNameTextBox = New System.Windows.Forms.TextBox()
        Me.passwordLabel = New System.Windows.Forms.Label()
        Me.passwordTextBox = New System.Windows.Forms.TextBox()
        Me.savePasswordCheckBox = New System.Windows.Forms.CheckBox()
        Me.sqlAuthenticationRadioButton = New System.Windows.Forms.RadioButton()
        Me.windowsAuthenticationRadioButton = New System.Windows.Forms.RadioButton()
        Me.databaseGroupBox = New System.Windows.Forms.GroupBox()
        Me.logicalDatabaseNameTextBox = New System.Windows.Forms.TextBox()
        Me.logicalDatabaseNameLabel = New System.Windows.Forms.Label()
        Me.attachDatabaseTableLayoutPanel = New System.Windows.Forms.TableLayoutPanel()
        Me.attachDatabaseTextBox = New System.Windows.Forms.TextBox()
        Me.browseButton = New System.Windows.Forms.Button()
        Me.attachDatabaseRadioButton = New System.Windows.Forms.RadioButton()
        Me.selectDatabaseComboBox = New System.Windows.Forms.ComboBox()
        Me.selectDatabaseRadioButton = New System.Windows.Forms.RadioButton()
        Me.OKButton = New System.Windows.Forms.Button()
        Me.TestButton = New System.Windows.Forms.Button()
        Me.AdvancedButton = New System.Windows.Forms.Button()
        Me.Cancel_Button = New System.Windows.Forms.Button()
        Me.serverTableLayoutPanel.SuspendLayout()
        Me.logonGroupBox.SuspendLayout()
        Me.LoginPanel.SuspendLayout()
        Me.databaseGroupBox.SuspendLayout()
        Me.attachDatabaseTableLayoutPanel.SuspendLayout()
        Me.SuspendLayout()
        '
        'serverLabel
        '
        Me.serverLabel.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.serverLabel.AutoSize = True
        Me.serverLabel.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.serverLabel.Location = New System.Drawing.Point(2, 7)
        Me.serverLabel.Name = "serverLabel"
        Me.serverLabel.Size = New System.Drawing.Size(70, 13)
        Me.serverLabel.TabIndex = 3
        Me.serverLabel.Text = "S&erver name:"
        '
        'serverTableLayoutPanel
        '
        Me.serverTableLayoutPanel.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.serverTableLayoutPanel.AutoSize = True
        Me.serverTableLayoutPanel.ColumnCount = 2
        Me.serverTableLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle())
        Me.serverTableLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle())
        Me.serverTableLayoutPanel.Controls.Add(Me.serverComboBox, 0, 0)
        Me.serverTableLayoutPanel.Controls.Add(Me.refreshButton, 1, 0)
        Me.serverTableLayoutPanel.Location = New System.Drawing.Point(5, 26)
        Me.serverTableLayoutPanel.Name = "serverTableLayoutPanel"
        Me.serverTableLayoutPanel.RowCount = 1
        Me.serverTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle())
        Me.serverTableLayoutPanel.Size = New System.Drawing.Size(356, 29)
        Me.serverTableLayoutPanel.TabIndex = 2
        '
        'serverComboBox
        '
        Me.serverComboBox.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.serverComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append
        Me.serverComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems
        Me.serverComboBox.FormattingEnabled = True
        Me.serverComboBox.Location = New System.Drawing.Point(3, 4)
        Me.serverComboBox.Name = "serverComboBox"
        Me.serverComboBox.Size = New System.Drawing.Size(269, 21)
        Me.serverComboBox.TabIndex = 0
        '
        'refreshButton
        '
        Me.refreshButton.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.refreshButton.Location = New System.Drawing.Point(278, 3)
        Me.refreshButton.MinimumSize = New System.Drawing.Size(75, 23)
        Me.refreshButton.Name = "refreshButton"
        Me.refreshButton.Size = New System.Drawing.Size(75, 23)
        Me.refreshButton.TabIndex = 1
        Me.refreshButton.Text = "&Refresh"
        '
        'logonGroupBox
        '
        Me.logonGroupBox.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.logonGroupBox.Controls.Add(Me.LoginPanel)
        Me.logonGroupBox.Controls.Add(Me.sqlAuthenticationRadioButton)
        Me.logonGroupBox.Controls.Add(Me.windowsAuthenticationRadioButton)
        Me.logonGroupBox.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.logonGroupBox.Location = New System.Drawing.Point(5, 62)
        Me.logonGroupBox.Name = "logonGroupBox"
        Me.logonGroupBox.Size = New System.Drawing.Size(350, 151)
        Me.logonGroupBox.TabIndex = 1
        Me.logonGroupBox.TabStop = False
        Me.logonGroupBox.Text = "Log on to the server"
        '
        'LoginPanel
        '
        Me.LoginPanel.Controls.Add(Me.userNameLabel)
        Me.LoginPanel.Controls.Add(Me.userNameTextBox)
        Me.LoginPanel.Controls.Add(Me.passwordLabel)
        Me.LoginPanel.Controls.Add(Me.passwordTextBox)
        Me.LoginPanel.Controls.Add(Me.savePasswordCheckBox)
        Me.LoginPanel.Location = New System.Drawing.Point(33, 64)
        Me.LoginPanel.Name = "LoginPanel"
        Me.LoginPanel.Size = New System.Drawing.Size(311, 81)
        Me.LoginPanel.TabIndex = 3
        '
        'userNameLabel
        '
        Me.userNameLabel.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.userNameLabel.AutoSize = True
        Me.userNameLabel.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.userNameLabel.Location = New System.Drawing.Point(2, 10)
        Me.userNameLabel.Margin = New System.Windows.Forms.Padding(3, 7, 3, 3)
        Me.userNameLabel.Name = "userNameLabel"
        Me.userNameLabel.Size = New System.Drawing.Size(61, 13)
        Me.userNameLabel.TabIndex = 10
        Me.userNameLabel.Text = "User name:"
        '
        'userNameTextBox
        '
        Me.userNameTextBox.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.userNameTextBox.Location = New System.Drawing.Point(69, 7)
        Me.userNameTextBox.Name = "userNameTextBox"
        Me.userNameTextBox.Size = New System.Drawing.Size(239, 20)
        Me.userNameTextBox.TabIndex = 11
        '
        'passwordLabel
        '
        Me.passwordLabel.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.passwordLabel.AutoSize = True
        Me.passwordLabel.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.passwordLabel.Location = New System.Drawing.Point(3, 36)
        Me.passwordLabel.Margin = New System.Windows.Forms.Padding(3, 7, 3, 3)
        Me.passwordLabel.Name = "passwordLabel"
        Me.passwordLabel.Size = New System.Drawing.Size(53, 13)
        Me.passwordLabel.TabIndex = 12
        Me.passwordLabel.Text = "&Password"
        '
        'passwordTextBox
        '
        Me.passwordTextBox.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.passwordTextBox.Location = New System.Drawing.Point(69, 33)
        Me.passwordTextBox.Name = "passwordTextBox"
        Me.passwordTextBox.PasswordChar = Global.Microsoft.VisualBasic.ChrW(42)
        Me.passwordTextBox.Size = New System.Drawing.Size(239, 20)
        Me.passwordTextBox.TabIndex = 13
        Me.passwordTextBox.UseSystemPasswordChar = True
        '
        'savePasswordCheckBox
        '
        Me.savePasswordCheckBox.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.savePasswordCheckBox.AutoSize = True
        Me.savePasswordCheckBox.Location = New System.Drawing.Point(69, 61)
        Me.savePasswordCheckBox.Margin = New System.Windows.Forms.Padding(3, 7, 3, 3)
        Me.savePasswordCheckBox.Name = "savePasswordCheckBox"
        Me.savePasswordCheckBox.Size = New System.Drawing.Size(115, 17)
        Me.savePasswordCheckBox.TabIndex = 14
        Me.savePasswordCheckBox.Text = "&Save my password"
        '
        'sqlAuthenticationRadioButton
        '
        Me.sqlAuthenticationRadioButton.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.sqlAuthenticationRadioButton.AutoSize = True
        Me.sqlAuthenticationRadioButton.Location = New System.Drawing.Point(12, 40)
        Me.sqlAuthenticationRadioButton.Name = "sqlAuthenticationRadioButton"
        Me.sqlAuthenticationRadioButton.Size = New System.Drawing.Size(173, 17)
        Me.sqlAuthenticationRadioButton.TabIndex = 1
        Me.sqlAuthenticationRadioButton.Text = "UserS&QL Server Authentication"
        '
        'windowsAuthenticationRadioButton
        '
        Me.windowsAuthenticationRadioButton.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.windowsAuthenticationRadioButton.AutoSize = True
        Me.windowsAuthenticationRadioButton.Checked = True
        Me.windowsAuthenticationRadioButton.Location = New System.Drawing.Point(12, 17)
        Me.windowsAuthenticationRadioButton.Name = "windowsAuthenticationRadioButton"
        Me.windowsAuthenticationRadioButton.Size = New System.Drawing.Size(162, 17)
        Me.windowsAuthenticationRadioButton.TabIndex = 2
        Me.windowsAuthenticationRadioButton.TabStop = True
        Me.windowsAuthenticationRadioButton.Text = "Use &Windows Authentication"
        '
        'databaseGroupBox
        '
        Me.databaseGroupBox.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.databaseGroupBox.Controls.Add(Me.logicalDatabaseNameTextBox)
        Me.databaseGroupBox.Controls.Add(Me.logicalDatabaseNameLabel)
        Me.databaseGroupBox.Controls.Add(Me.attachDatabaseTableLayoutPanel)
        Me.databaseGroupBox.Controls.Add(Me.attachDatabaseRadioButton)
        Me.databaseGroupBox.Controls.Add(Me.selectDatabaseComboBox)
        Me.databaseGroupBox.Controls.Add(Me.selectDatabaseRadioButton)
        Me.databaseGroupBox.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.databaseGroupBox.Location = New System.Drawing.Point(5, 219)
        Me.databaseGroupBox.Margin = New System.Windows.Forms.Padding(0, 3, 0, 0)
        Me.databaseGroupBox.Name = "databaseGroupBox"
        Me.databaseGroupBox.Size = New System.Drawing.Size(350, 175)
        Me.databaseGroupBox.TabIndex = 3
        Me.databaseGroupBox.TabStop = False
        Me.databaseGroupBox.Text = "Connect to a database"
        '
        'logicalDatabaseNameTextBox
        '
        Me.logicalDatabaseNameTextBox.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.logicalDatabaseNameTextBox.Location = New System.Drawing.Point(30, 138)
        Me.logicalDatabaseNameTextBox.Name = "logicalDatabaseNameTextBox"
        Me.logicalDatabaseNameTextBox.Size = New System.Drawing.Size(308, 20)
        Me.logicalDatabaseNameTextBox.TabIndex = 0
        '
        'logicalDatabaseNameLabel
        '
        Me.logicalDatabaseNameLabel.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.logicalDatabaseNameLabel.AutoSize = True
        Me.logicalDatabaseNameLabel.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.logicalDatabaseNameLabel.Location = New System.Drawing.Point(30, 123)
        Me.logicalDatabaseNameLabel.Margin = New System.Windows.Forms.Padding(27, 0, 9, 0)
        Me.logicalDatabaseNameLabel.Name = "logicalDatabaseNameLabel"
        Me.logicalDatabaseNameLabel.Size = New System.Drawing.Size(73, 13)
        Me.logicalDatabaseNameLabel.TabIndex = 1
        Me.logicalDatabaseNameLabel.Text = "&Logical name:"
        '
        'attachDatabaseTableLayoutPanel
        '
        Me.attachDatabaseTableLayoutPanel.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.attachDatabaseTableLayoutPanel.AutoSize = True
        Me.attachDatabaseTableLayoutPanel.ColumnCount = 2
        Me.attachDatabaseTableLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle())
        Me.attachDatabaseTableLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle())
        Me.attachDatabaseTableLayoutPanel.Controls.Add(Me.attachDatabaseTextBox, 0, 0)
        Me.attachDatabaseTableLayoutPanel.Controls.Add(Me.browseButton, 1, 0)
        Me.attachDatabaseTableLayoutPanel.Location = New System.Drawing.Point(30, 93)
        Me.attachDatabaseTableLayoutPanel.Margin = New System.Windows.Forms.Padding(27, 0, 9, 3)
        Me.attachDatabaseTableLayoutPanel.MaximumSize = New System.Drawing.Size(308, 28)
        Me.attachDatabaseTableLayoutPanel.Name = "attachDatabaseTableLayoutPanel"
        Me.attachDatabaseTableLayoutPanel.RowCount = 1
        Me.attachDatabaseTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle())
        Me.attachDatabaseTableLayoutPanel.Size = New System.Drawing.Size(308, 28)
        Me.attachDatabaseTableLayoutPanel.TabIndex = 3
        '
        'attachDatabaseTextBox
        '
        Me.attachDatabaseTextBox.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.attachDatabaseTextBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend
        Me.attachDatabaseTextBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.FileSystem
        Me.attachDatabaseTextBox.Location = New System.Drawing.Point(3, 4)
        Me.attachDatabaseTextBox.Margin = New System.Windows.Forms.Padding(3, 0, 3, 0)
        Me.attachDatabaseTextBox.Name = "attachDatabaseTextBox"
        Me.attachDatabaseTextBox.Size = New System.Drawing.Size(223, 20)
        Me.attachDatabaseTextBox.TabIndex = 0
        '
        'browseButton
        '
        Me.browseButton.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.browseButton.Location = New System.Drawing.Point(232, 3)
        Me.browseButton.MinimumSize = New System.Drawing.Size(75, 23)
        Me.browseButton.Name = "browseButton"
        Me.browseButton.Size = New System.Drawing.Size(75, 23)
        Me.browseButton.TabIndex = 1
        Me.browseButton.Text = "&Browse..."
        '
        'attachDatabaseRadioButton
        '
        Me.attachDatabaseRadioButton.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.attachDatabaseRadioButton.Location = New System.Drawing.Point(12, 75)
        Me.attachDatabaseRadioButton.Margin = New System.Windows.Forms.Padding(9, 3, 9, 0)
        Me.attachDatabaseRadioButton.Name = "attachDatabaseRadioButton"
        Me.attachDatabaseRadioButton.Size = New System.Drawing.Size(137, 18)
        Me.attachDatabaseRadioButton.TabIndex = 2
        Me.attachDatabaseRadioButton.Text = "Attac&h a database file:"
        '
        'selectDatabaseComboBox
        '
        Me.selectDatabaseComboBox.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.selectDatabaseComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append
        Me.selectDatabaseComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems
        Me.selectDatabaseComboBox.FormattingEnabled = True
        Me.selectDatabaseComboBox.Location = New System.Drawing.Point(33, 48)
        Me.selectDatabaseComboBox.Name = "selectDatabaseComboBox"
        Me.selectDatabaseComboBox.Size = New System.Drawing.Size(305, 21)
        Me.selectDatabaseComboBox.TabIndex = 4
        '
        'selectDatabaseRadioButton
        '
        Me.selectDatabaseRadioButton.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.selectDatabaseRadioButton.AutoSize = True
        Me.selectDatabaseRadioButton.Checked = True
        Me.selectDatabaseRadioButton.Location = New System.Drawing.Point(12, 22)
        Me.selectDatabaseRadioButton.Name = "selectDatabaseRadioButton"
        Me.selectDatabaseRadioButton.Size = New System.Drawing.Size(182, 17)
        Me.selectDatabaseRadioButton.TabIndex = 5
        Me.selectDatabaseRadioButton.TabStop = True
        Me.selectDatabaseRadioButton.Text = "Select or enter a &database name:"
        '
        'OKButton
        '
        Me.OKButton.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.OKButton.Location = New System.Drawing.Point(12, 399)
        Me.OKButton.Name = "OKButton"
        Me.OKButton.Size = New System.Drawing.Size(75, 23)
        Me.OKButton.TabIndex = 4
        Me.OKButton.Text = "OK"
        Me.OKButton.UseVisualStyleBackColor = True
        '
        'TestButton
        '
        Me.TestButton.Location = New System.Drawing.Point(174, 399)
        Me.TestButton.Name = "TestButton"
        Me.TestButton.Size = New System.Drawing.Size(96, 23)
        Me.TestButton.TabIndex = 6
        Me.TestButton.Text = "Test Connection"
        Me.TestButton.UseVisualStyleBackColor = True
        '
        'AdvancedButton
        '
        Me.AdvancedButton.Location = New System.Drawing.Point(276, 399)
        Me.AdvancedButton.Name = "AdvancedButton"
        Me.AdvancedButton.Size = New System.Drawing.Size(75, 23)
        Me.AdvancedButton.TabIndex = 7
        Me.AdvancedButton.Text = "Advanced"
        Me.AdvancedButton.UseVisualStyleBackColor = True
        '
        'Cancel_Button
        '
        Me.Cancel_Button.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Cancel_Button.Location = New System.Drawing.Point(93, 399)
        Me.Cancel_Button.Name = "Cancel_Button"
        Me.Cancel_Button.Size = New System.Drawing.Size(75, 23)
        Me.Cancel_Button.TabIndex = 8
        Me.Cancel_Button.Text = "Cancel"
        Me.Cancel_Button.UseVisualStyleBackColor = True
        '
        'SQLConnectionDialog
        '
        Me.AcceptButton = Me.OKButton
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit
        Me.CancelButton = Me.Cancel_Button
        Me.ClientSize = New System.Drawing.Size(363, 434)
        Me.Controls.Add(Me.Cancel_Button)
        Me.Controls.Add(Me.AdvancedButton)
        Me.Controls.Add(Me.TestButton)
        Me.Controls.Add(Me.OKButton)
        Me.Controls.Add(Me.databaseGroupBox)
        Me.Controls.Add(Me.logonGroupBox)
        Me.Controls.Add(Me.serverTableLayoutPanel)
        Me.Controls.Add(Me.serverLabel)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Me.Name = "SQLConnectionDialog"
        Me.Text = "SQL Connection"
        Me.serverTableLayoutPanel.ResumeLayout(False)
        Me.logonGroupBox.ResumeLayout(False)
        Me.logonGroupBox.PerformLayout()
        Me.LoginPanel.ResumeLayout(False)
        Me.LoginPanel.PerformLayout()
        Me.databaseGroupBox.ResumeLayout(False)
        Me.databaseGroupBox.PerformLayout()
        Me.attachDatabaseTableLayoutPanel.ResumeLayout(False)
        Me.attachDatabaseTableLayoutPanel.PerformLayout()
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub

    Public Sub LoadProperties() Implements IDataConnectionUIControl.LoadProperties
        Me._loading = True
        If (Me.currentOleDBProvider <> Me.Properties.Provider) Then
            Me.selectDatabaseComboBox.Items.Clear()
            Me.currentOleDBProvider = Me.Properties.Provider
        End If
        Me.serverComboBox.Text = Me.Properties.ServerName
        If Me.Properties.UseWindowsAuthentication Then
            Me.windowsAuthenticationRadioButton.Checked = True
        Else
            Me.sqlAuthenticationRadioButton.Checked = True
        End If
        If (Me.currentUserInstanceSetting <> Me.Properties.UserInstance) Then
            Me.selectDatabaseComboBox.Items.Clear()
        End If
        Me.currentUserInstanceSetting = Me.Properties.UserInstance
        Me.userNameTextBox.Text = Me.Properties.UserName
        Me.passwordTextBox.Text = Me.Properties.Password
        Me.savePasswordCheckBox.Checked = Me.Properties.SavePassword
        If ((Me.Properties.DatabaseFile Is Nothing) OrElse (Me.Properties.DatabaseFile.Length = 0)) Then
            Me.selectDatabaseRadioButton.Checked = True
            Me.selectDatabaseComboBox.Text = Me.Properties.DatabaseName
            Me.attachDatabaseTextBox.Text = Nothing
            Me.logicalDatabaseNameTextBox.Text = Nothing
        Else
            Me.attachDatabaseRadioButton.Checked = True
            Me.selectDatabaseComboBox.Text = Nothing
            Me.attachDatabaseTextBox.Text = Me.Properties.DatabaseFile
            Me.logicalDatabaseNameTextBox.Text = Me.Properties.LogicalDatabaseName
        End If
        Me._loading = False
    End Sub

    Protected Overrides Sub OnParentChanged(ByVal e As EventArgs)
        MyBase.OnParentChanged(e)
        If (MyBase.Parent Is Nothing) Then
            Me.OnFontChanged(e)
        End If
    End Sub

    Protected Overrides Sub OnRightToLeftChanged(ByVal e As EventArgs)
        MyBase.OnRightToLeftChanged(e)
        If (((Not MyBase.ParentForm Is Nothing) AndAlso MyBase.ParentForm.RightToLeftLayout) AndAlso (Me.RightToLeft = RightToLeft.Yes)) Then
            LayoutUtils.MirrorControl(Me.serverLabel, Me.serverTableLayoutPanel)
            LayoutUtils.MirrorControl(Me.windowsAuthenticationRadioButton)
            LayoutUtils.MirrorControl(Me.sqlAuthenticationRadioButton)
            LayoutUtils.MirrorControl(LoginPanel)
            LayoutUtils.MirrorControl(Me.selectDatabaseRadioButton)
            LayoutUtils.MirrorControl(Me.selectDatabaseComboBox)
            LayoutUtils.MirrorControl(Me.attachDatabaseRadioButton)
            LayoutUtils.MirrorControl(Me.attachDatabaseTableLayoutPanel)
            LayoutUtils.MirrorControl(Me.logicalDatabaseNameLabel)
            LayoutUtils.MirrorControl(Me.logicalDatabaseNameTextBox)
        Else
            LayoutUtils.UnmirrorControl(Me.logicalDatabaseNameTextBox)
            LayoutUtils.UnmirrorControl(Me.logicalDatabaseNameLabel)
            LayoutUtils.UnmirrorControl(Me.attachDatabaseTableLayoutPanel)
            LayoutUtils.UnmirrorControl(Me.attachDatabaseRadioButton)
            LayoutUtils.UnmirrorControl(Me.selectDatabaseComboBox)
            LayoutUtils.UnmirrorControl(Me.selectDatabaseRadioButton)
            LayoutUtils.UnmirrorControl(Me.LoginPanel)
            LayoutUtils.UnmirrorControl(Me.sqlAuthenticationRadioButton)
            LayoutUtils.UnmirrorControl(Me.windowsAuthenticationRadioButton)
            LayoutUtils.UnmirrorControl(Me.serverLabel, Me.serverTableLayoutPanel)
        End If
    End Sub

    Private Sub PopulateDatabaseComboBox()
        If (Me.selectDatabaseComboBox.Items.Count = 0) Then
            If (Me._databases.Length > 0) Then
                Me.selectDatabaseComboBox.Items.AddRange(Me._databases)
            Else
                Me.selectDatabaseComboBox.Items.Add(String.Empty)
            End If
        End If
        Me._databaseEnumerationThread = Nothing
    End Sub

    Private Sub PopulateServerComboBox()
        If (Me.serverComboBox.Items.Count = 0) Then
            If (Me._servers.Length > 0) Then
                Me.serverComboBox.Items.AddRange(Me._servers)
            Else
                Me.serverComboBox.Items.Add(String.Empty)
            End If
        End If
    End Sub

    <UIPermission(SecurityAction.LinkDemand, Window:=UIPermissionWindow.AllWindows)> _
    Protected Overrides Function ProcessDialogKey(ByVal keyData As Keys) As Boolean
        If ((MyBase.ActiveControl Is Me.selectDatabaseRadioButton) AndAlso ((keyData And Keys.KeyCode) = Keys.Down)) Then
            Me.attachDatabaseRadioButton.Focus()
            Return True
        End If
        If ((MyBase.ActiveControl Is Me.attachDatabaseRadioButton) AndAlso ((keyData And Keys.KeyCode) = Keys.Down)) Then
            Me.selectDatabaseRadioButton.Focus()
            Return True
        End If
        Return MyBase.ProcessDialogKey(keyData)
    End Function

    Private Sub RefreshServers(ByVal sender As Object, ByVal e As EventArgs) Handles refreshButton.Click
        Me.serverComboBox.Items.Clear()
        Me.EnumerateServers(sender, e)
    End Sub

    Protected Overrides Sub ScaleControl(ByVal factor As SizeF, ByVal specified As BoundsSpecified)
        Dim size As Size = MyBase.Size
        Me.MinimumSize = size.Empty
        MyBase.ScaleControl(factor, specified)
        Me.MinimumSize = New Size(CInt(Math.Round(CDbl((size.Width * factor.Width)))), CInt(Math.Round(CDbl((size.Height * factor.Height)))))
    End Sub

    Private Sub SetAttachDatabase(ByVal sender As Object, ByVal e As EventArgs) Handles attachDatabaseTextBox.TextChanged
        If Not Me._loading Then
            If Me.selectDatabaseRadioButton.Checked Then
                Me.Properties.DatabaseFile = Nothing
            Else
                Me.Properties.DatabaseFile = Me.attachDatabaseTextBox.Text
            End If
        End If
    End Sub

    Private Sub SetAuthenticationOption(ByVal sender As Object, ByVal e As EventArgs) Handles sqlAuthenticationRadioButton.CheckedChanged
        If Me.windowsAuthenticationRadioButton.Checked Then
            If Not Me._loading Then
                Me.Properties.UseWindowsAuthentication = True
                Me.Properties.UserName = Nothing
                Me.Properties.Password = Nothing
                Me.Properties.SavePassword = False
            End If
            Me.LoginPanel.Enabled = False
        Else
            If Not Me._loading Then
                Me.Properties.UseWindowsAuthentication = False
                Me.SetUserName(sender, e)
                Me.SetPassword(sender, e)
                Me.SetSavePassword(sender, e)
            End If
            Me.LoginPanel.Enabled = True
        End If
        Me.SetDatabaseGroupBoxStatus(sender, e)
        Me.selectDatabaseComboBox.Items.Clear()
    End Sub

    Private Sub SetDatabase(ByVal sender As Object, ByVal e As EventArgs) Handles selectDatabaseComboBox.TextChanged
        If Not Me._loading Then
            Me.Properties.DatabaseName = Me.selectDatabaseComboBox.Text
            If ((Me.selectDatabaseComboBox.Items.Count = 0) AndAlso (Me._databaseEnumerationThread Is Nothing)) Then
                Me._databaseEnumerationThread = New Thread(New ThreadStart(AddressOf Me.EnumerateDatabases))
                Me._databaseEnumerationThread.Start()
            End If
        End If
    End Sub

    Private Sub SetDatabaseGroupBoxStatus(ByVal sender As Object, ByVal e As EventArgs)
        If ((Me.serverComboBox.Text.Trim.Length > 0) AndAlso (Me.windowsAuthenticationRadioButton.Checked OrElse (Me.userNameTextBox.Text.Trim.Length > 0))) Then
            Me.databaseGroupBox.Enabled = True
        Else
            Me.databaseGroupBox.Enabled = False
        End If
    End Sub

    Private Sub SetDatabaseOption(ByVal sender As Object, ByVal e As EventArgs) Handles attachDatabaseRadioButton.CheckedChanged
        If Me.selectDatabaseRadioButton.Checked Then
            Me.SetDatabase(sender, e)
            Me.SetAttachDatabase(sender, e)
            Me.selectDatabaseComboBox.Enabled = True
            Me.attachDatabaseTableLayoutPanel.Enabled = False
            Me.logicalDatabaseNameLabel.Enabled = False
            Me.logicalDatabaseNameTextBox.Enabled = False
        Else
            Me.SetAttachDatabase(sender, e)
            Me.SetLogicalFilename(sender, e)
            Me.selectDatabaseComboBox.Enabled = False
            Me.attachDatabaseTableLayoutPanel.Enabled = True
            Me.logicalDatabaseNameLabel.Enabled = True
            Me.logicalDatabaseNameTextBox.Enabled = True
        End If
    End Sub

    Private Sub SetLogicalFilename(ByVal sender As Object, ByVal e As EventArgs) Handles logicalDatabaseNameTextBox.TextChanged
        If Not Me._loading Then
            If Me.selectDatabaseRadioButton.Checked Then
                Me.Properties.LogicalDatabaseName = Nothing
            Else
                Me.Properties.LogicalDatabaseName = Me.logicalDatabaseNameTextBox.Text
            End If
        End If
    End Sub

    Private Sub SetPassword(ByVal sender As Object, ByVal e As EventArgs) Handles passwordTextBox.TextChanged
        If Not Me._loading Then
            Me.Properties.Password = Me.passwordTextBox.Text
            Me.passwordTextBox.Text = Me.passwordTextBox.Text
        End If
        Me.selectDatabaseComboBox.Items.Clear()
    End Sub

    Private Sub SetSavePassword(ByVal sender As Object, ByVal e As EventArgs) Handles savePasswordCheckBox.CheckedChanged
        If Not Me._loading Then
            Me.Properties.SavePassword = Me.savePasswordCheckBox.Checked
        End If
    End Sub

    Private Sub SetServer(ByVal sender As Object, ByVal e As EventArgs) Handles serverComboBox.TextChanged
        If Not Me._loading Then
            Me.Properties.ServerName = Me.serverComboBox.Text
            If ((Me.serverComboBox.Items.Count = 0) AndAlso (Me._serverEnumerationThread Is Nothing)) Then
                Me._serverEnumerationThread = New Thread(New ThreadStart(AddressOf Me.EnumerateServers))
                Me._serverEnumerationThread.Start()
            End If
        End If
        Me.SetDatabaseGroupBoxStatus(sender, e)
        Me.selectDatabaseComboBox.Items.Clear()
    End Sub

    Private Sub SetUserName(ByVal sender As Object, ByVal e As EventArgs) Handles userNameTextBox.TextChanged
        If Not Me._loading Then
            Me.Properties.UserName = Me.userNameTextBox.Text
        End If
        Me.SetDatabaseGroupBoxStatus(sender, e)
        Me.selectDatabaseComboBox.Items.Clear()
    End Sub

    Private Shared Function TextWithoutMnemonics(ByVal [text] As String) As String
        If ([text] Is Nothing) Then
            Return Nothing
        End If
        Dim index As Integer = [text].IndexOf("&"c)
        If (index = -1) Then
            Return [text]
        End If
        Dim builder As New StringBuilder([text].Substring(0, index))
        Do While (index < [text].Length)
            If ([text].Chars(index) = "&"c) Then
                index += 1
            End If
            If (index < [text].Length) Then
                builder.Append([text].Chars(index))
            End If
            index += 1
        Loop
        Return builder.ToString
    End Function

    Private Sub TrimControlText(ByVal sender As Object, ByVal e As EventArgs) Handles attachDatabaseTextBox.Leave
        Dim control As Control = TryCast(sender, Control)
        control.Text = control.Text.Trim
    End Sub


    ' Properties
    Private ReadOnly Property Properties As ControlProperties
        Get
            Return Me._controlProperties
        End Get
    End Property


    ' Fields
    Private _controlProperties As ControlProperties
    Private _databaseEnumerationThread As Thread
    Private _databases As Object()
    Private _loading As Boolean = False
    Private _serverEnumerationThread As Thread
    Private _servers As Object()
    Private _uiThread As Thread
    Private WithEvents attachDatabaseRadioButton As RadioButton
    Private WithEvents attachDatabaseTableLayoutPanel As TableLayoutPanel
    Private WithEvents attachDatabaseTextBox As TextBox
    Private WithEvents browseButton As Button
    Private components As IContainer
    Private currentOleDBProvider As String
    Private currentUserInstanceSetting As Boolean
    Private WithEvents databaseGroupBox As GroupBox
    Private WithEvents logicalDatabaseNameLabel As Label
    Private WithEvents logicalDatabaseNameTextBox As TextBox
    Private WithEvents logonGroupBox As GroupBox
    Private WithEvents refreshButton As Button
    Private WithEvents selectDatabaseComboBox As ComboBox
    Private WithEvents selectDatabaseRadioButton As RadioButton
    Private WithEvents serverComboBox As ComboBox
    Private WithEvents serverLabel As Label
    Private WithEvents serverTableLayoutPanel As TableLayoutPanel
    Private WithEvents sqlAuthenticationRadioButton As RadioButton
    Private WithEvents windowsAuthenticationRadioButton As RadioButton

    ' Nested Types
    Private Class ControlProperties
        ' Methods
        Public Sub New(ByVal properties As IDataConnectionProperties)
            Me._properties = properties
        End Sub


        Public Function GetBasicConnection() As IDbConnection
            Dim connection As IDbConnection = Nothing
            Dim connectionString As String = String.Empty
            If (TypeOf Me._properties Is SqlConnectionProperties OrElse TypeOf Me._properties Is OleDBConnectionProperties) Then
                If TypeOf Me._properties Is OleDBConnectionProperties Then
                    connectionString = (connectionString & "Provider=" & Me._properties.Item("Provider").ToString & ";")
                End If
                connectionString = (connectionString & "Data Source='" & Me.ServerName.Replace("'", "''") & "';")
                If Me.UserInstance Then
                    connectionString = (connectionString & "User Instance=true;")
                End If
                If Me.UseWindowsAuthentication Then
                    connectionString = (connectionString & "Integrated Security=" & Me._properties.Item("Integrated Security").ToString & ";")
                Else
                    connectionString = ((connectionString & "User ID='" & Me.UserName.Replace("'", "''") & "';") & "Password='" & Me.Password.Replace("'", "''") & "';")
                End If
                If TypeOf Me._properties Is SqlConnectionProperties Then
                    connectionString = (connectionString & "Pooling=False;")
                End If
            End If
            If TypeOf Me._properties Is OdbcConnectionProperties Then
                connectionString = ((connectionString & "DRIVER={SQL Server};") & "SERVER={" & Me.ServerName.Replace("}", "}}") & "};")
                If Me.UseWindowsAuthentication Then
                    connectionString = (connectionString & "Trusted_Connection=Yes;")
                Else
                    connectionString = ((connectionString & "UID={" & Me.UserName.Replace("}", "}}") & "};") & "PWD={" & Me.Password.Replace("}", "}}") & "};")
                End If
            End If
            If TypeOf Me._properties Is SqlConnectionProperties Then
                connection = New SqlConnection(connectionString)
            End If
            If TypeOf Me._properties Is OleDBConnectionProperties Then
                connection = New OleDbConnection(connectionString)
            End If
            If TypeOf Me._properties Is OdbcConnectionProperties Then
                connection = New OdbcConnection(connectionString)
            End If
            Return connection
        End Function

        ' Properties
        Public Property DatabaseFile As String
            Get
                Return TryCast(Me._properties.Item(Me.DatabaseFileProperty), String)
            End Get
            Set(ByVal value As String)
                If ((Not value Is Nothing) AndAlso (value.Trim.Length > 0)) Then
                    Me._properties.Item(Me.DatabaseFileProperty) = value.Trim
                Else
                    Me._properties.Reset(Me.DatabaseFileProperty)
                End If
            End Set
        End Property

        Private ReadOnly Property DatabaseFileProperty As String
            Get
                If TypeOf Me._properties Is SqlConnectionProperties Then
                    Return "AttachDbFilename"
                End If
                If TypeOf Me._properties Is OleDBConnectionProperties Then
                    Return "Initial File Name"
                End If
                If TypeOf Me._properties Is OdbcConnectionProperties Then
                    Return "AttachDBFileName"
                End If
                Return Nothing
            End Get
        End Property

        Public Property DatabaseName As String
            Get
                Return TryCast(Me._properties.Item(Me.DatabaseNameProperty), String)
            End Get
            Set(ByVal value As String)
                If ((Not value Is Nothing) AndAlso (value.Trim.Length > 0)) Then
                    Me._properties.Item(Me.DatabaseNameProperty) = value.Trim
                Else
                    Me._properties.Reset(Me.DatabaseNameProperty)
                End If
            End Set
        End Property

        Private ReadOnly Property DatabaseNameProperty As String
            Get
                If TypeOf Me._properties Is SqlConnectionProperties Then
                    Return "Initial Catalog"
                End If
                If TypeOf Me._properties Is OleDBConnectionProperties Then
                    Return "Initial Catalog"
                End If
                If TypeOf Me._properties Is OdbcConnectionProperties Then
                    Return "DATABASE"
                End If
                Return Nothing
            End Get
        End Property

        Public Property LogicalDatabaseName As String
            Get
                Return Me.DatabaseName
            End Get
            Set(ByVal value As String)
                Me.DatabaseName = value
            End Set
        End Property

        Public Property Password As String
            Get
                Return TryCast(Me._properties.Item(Me.PasswordProperty), String)
            End Get
            Set(ByVal value As String)
                If ((Not value Is Nothing) AndAlso (value.Length > 0)) Then
                    Me._properties.Item(Me.PasswordProperty) = value
                Else
                    Me._properties.Reset(Me.PasswordProperty)
                End If
            End Set
        End Property

        Private ReadOnly Property PasswordProperty As String
            Get
                If TypeOf Me._properties Is SqlConnectionProperties Then
                    Return "Password"
                End If
                If TypeOf Me._properties Is OleDBConnectionProperties Then
                    Return "Password"
                End If
                If TypeOf Me._properties Is OdbcConnectionProperties Then
                    Return "PWD"
                End If
                Return Nothing
            End Get
        End Property

        Public ReadOnly Property Provider As String
            Get
                If TypeOf Me._properties Is OleDBSqlConnectionProperties Then
                    Return TryCast(Me._properties.Item("Provider"), String)
                End If
                Return Nothing
            End Get
        End Property

        Public Property SavePassword As Boolean
            Get
                If TypeOf Me._properties Is OdbcConnectionProperties Then
                    Return False
                End If
                Return CBool(Me._properties.Item("Persist Security Info"))
            End Get
            Set(ByVal value As Boolean)
                If value Then
                    Me._properties.Item("Persist Security Info") = value
                Else
                    Me._properties.Reset("Persist Security Info")
                End If
            End Set
        End Property

        Public Property ServerName As String
            Get
                Return TryCast(Me._properties.Item(Me.ServerNameProperty), String)
            End Get
            Set(ByVal value As String)
                If ((Not value Is Nothing) AndAlso (value.Trim.Length > 0)) Then
                    Me._properties.Item(Me.ServerNameProperty) = value.Trim
                Else
                    Me._properties.Reset(Me.ServerNameProperty)
                End If
            End Set
        End Property

        Private ReadOnly Property ServerNameProperty As String
            Get
                If TypeOf Me._properties Is SqlConnectionProperties Then
                    Return "Data Source"
                End If
                If TypeOf Me._properties Is OleDBConnectionProperties Then
                    Return "Data Source"
                End If
                If TypeOf Me._properties Is OdbcConnectionProperties Then
                    Return "SERVER"
                End If
                Return Nothing
            End Get
        End Property

        Public ReadOnly Property UserInstance As Boolean
            Get
                Return (TypeOf Me._properties Is SqlConnectionProperties AndAlso CBool(Me._properties.Item("User Instance")))
            End Get
        End Property

        Public Property UserName As String
            Get
                Return TryCast(Me._properties.Item(Me.UserNameProperty), String)
            End Get
            Set(ByVal value As String)
                If ((Not value Is Nothing) AndAlso (value.Trim.Length > 0)) Then
                    Me._properties.Item(Me.UserNameProperty) = value.Trim
                Else
                    Me._properties.Reset(Me.UserNameProperty)
                End If
            End Set
        End Property

        Private ReadOnly Property UserNameProperty As String
            Get
                If TypeOf Me._properties Is SqlConnectionProperties Then
                    Return "User ID"
                End If
                If TypeOf Me._properties Is OleDBConnectionProperties Then
                    Return "User ID"
                End If
                If TypeOf Me._properties Is OdbcConnectionProperties Then
                    Return "UID"
                End If
                Return Nothing
            End Get
        End Property

        Public Property UseWindowsAuthentication As Boolean
            Get
                If TypeOf Me._properties Is SqlConnectionProperties Then
                    Return CBool(Me._properties.Item("Integrated Security"))
                End If
                If TypeOf Me._properties Is OleDBConnectionProperties Then
                    Return ((Me._properties.Contains("Integrated Security") AndAlso TypeOf Me._properties.Item("Integrated Security") Is String) AndAlso TryCast(Me._properties.Item("Integrated Security"), String).Equals("SSPI", StringComparison.OrdinalIgnoreCase))
                End If
                Return (TypeOf Me._properties Is OdbcConnectionProperties AndAlso ((Me._properties.Contains("Trusted_Connection") AndAlso TypeOf Me._properties.Item("Trusted_Connection") Is String) AndAlso TryCast(Me._properties.Item("Trusted_Connection"), String).Equals("Yes", StringComparison.OrdinalIgnoreCase)))
            End Get
            Set(ByVal value As Boolean)
                If TypeOf Me._properties Is SqlConnectionProperties Then
                    If value Then
                        Me._properties.Item("Integrated Security") = value
                    Else
                        Me._properties.Reset("Integrated Security")
                    End If
                End If
                If TypeOf Me._properties Is OleDBConnectionProperties Then
                    If value Then
                        Me._properties.Item("Integrated Security") = "SSPI"
                    Else
                        Me._properties.Reset("Integrated Security")
                    End If
                End If
                If TypeOf Me._properties Is OdbcConnectionProperties Then
                    If value Then
                        Me._properties.Item("Trusted_Connection") = "Yes"
                    Else
                        Me._properties.Remove("Trusted_Connection")
                    End If
                End If
            End Set
        End Property

        ReadOnly Property ConnectionProperties As IDataConnectionProperties
            Get
                Return _properties
            End Get
        End Property

        ' Fields
        Private _properties As IDataConnectionProperties
    End Class


    Public ReadOnly Property ConnectionString As String
        Get
            Dim Value As String = ""
            Dim Connect = Properties.ConnectionProperties
            If TypeOf Connect Is SqlConnectionProperties Then
                Dim Sqlconnection = DirectCast(Connect, SqlConnectionProperties)
                Value = Sqlconnection.ConnectionStringBuilder.ConnectionString
                Sqlconnection = Nothing
            ElseIf TypeOf Connect Is OleDBConnectionProperties Then
                Dim OleDBConnection = DirectCast(Connect, OleDBConnectionProperties)
                Value = OleDBConnection.ConnectionStringBuilder.ConnectionString
                OleDBConnection = Nothing
            ElseIf TypeOf Connect Is OdbcConnectionProperties Then
                Dim odbcConnection = DirectCast(Connect, OdbcConnectionProperties)
                Value = odbcConnection.ConnectionStringBuilder.ConnectionString
                odbcConnection = Nothing
            End If
            Return Value
        End Get
    End Property

    Public ReadOnly Property DeploymentConnectionString As String
        Get
            Return Properties.GetBasicConnection.ConnectionString
        End Get
    End Property

    Public ReadOnly Property TargetDatabase As String
        Get
            Return Properties.DatabaseName
        End Get
    End Property

    Private Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OKButton.Click
        Me.DialogResult = DialogResult.OK
        Me.Close()
    End Sub

    Private Sub CancelButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 'Handles Cancel_Button.Click
        Me.DialogResult = DialogResult.Cancel
        Me.Close()
    End Sub

    Private WithEvents userNameLabel As System.Windows.Forms.Label
    Private WithEvents userNameTextBox As System.Windows.Forms.TextBox
    Private WithEvents passwordLabel As System.Windows.Forms.Label
    Private WithEvents passwordTextBox As System.Windows.Forms.TextBox
    Private WithEvents savePasswordCheckBox As System.Windows.Forms.CheckBox
    'Friend WithEvents AdvanceButton As System.Windows.Forms.Button

    Private Sub AdvancedButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AdvancedButton.Click
        Try
            Dim frm As New Form
            Dim pg As PropertyGrid = New PropertyGrid
            frm.Text = "Connection Properties"
            With frm
                .ShowInTaskbar = False
                .ShowIcon = False
                .FormBorderStyle = Windows.Forms.FormBorderStyle.SizableToolWindow
                .StartPosition = FormStartPosition.CenterParent
            End With
            If TypeOf Properties.ConnectionProperties Is SqlConnectionProperties Then
                pg.SelectedObject = DirectCast(Properties.ConnectionProperties, SqlConnectionProperties)
            ElseIf TypeOf Properties.ConnectionProperties Is OdbcConnectionProperties Then
                pg.SelectedObject = DirectCast(Properties.ConnectionProperties, OdbcConnectionProperties)
            ElseIf TypeOf Properties.ConnectionProperties Is OleDBConnectionProperties Then
                pg.SelectedObject = DirectCast(Properties.ConnectionProperties, OleDBConnectionProperties)
            Else
                Throw New InvalidOperationException("Unknown Connection Properties Type.")
            End If
            pg.Dock = DockStyle.Fill
            pg.Parent = frm
            frm.ShowDialog(Me)
        Catch ex As Exception
            Dialogs.ExceptionDialog.DisplayException(ex)
        End Try
    End Sub

    Private Sub TestButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TestButton.Click
        Me.Cursor = Cursors.WaitCursor
        Try
            If TypeOf Properties.ConnectionProperties Is SqlConnectionProperties Then
                Dim Con = DirectCast(Properties.ConnectionProperties, SqlConnectionProperties)
                Try
                    Con.Test()
                    MsgBox("Test succesful.", MsgBoxStyle.Information, "Success")
                Catch ex As InvalidOperationException
                    MsgBox(ex.Message, MsgBoxStyle.Information, "Nonexistant Database")
                Catch ex As Exception
                    'Do something 
                    MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Connection Error")
                End Try
            ElseIf TypeOf Properties.ConnectionProperties Is OdbcConnectionProperties Then
                Dim Con = DirectCast(Properties.ConnectionProperties, OdbcConnectionProperties)
                Try
                    Con.Test()
                    MsgBox("Test succesful.", MsgBoxStyle.Information, "Success")
                Catch ex As Exception
                    MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Connection Error")
                End Try
            ElseIf TypeOf Properties.ConnectionProperties Is OleDBConnectionProperties Then
                Dim Con = DirectCast(Properties.ConnectionProperties, OleDBConnectionProperties)
                Try
                    Con.Test()
                    MsgBox("Test succesful.", MsgBoxStyle.Information, "Success")
                Catch ex As Exception
                    MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Connection Error")
                End Try
            Else
                Throw New InvalidOperationException("Unknown Connection Properties Type.")
            End If
        Catch ex As Exception
            Dialogs.ExceptionDialog.DisplayException(ex)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub
    Friend WithEvents OKButton As System.Windows.Forms.Button
    'Friend WithEvents Cancel_Button As System.Windows.Forms.Button
    Friend WithEvents TestButton As System.Windows.Forms.Button
    Friend WithEvents AdvancedButton As System.Windows.Forms.Button
    Friend WithEvents LoginPanel As System.Windows.Forms.Panel
    Friend WithEvents Cancel_Button As System.Windows.Forms.Button

    Private _DenyAttachFile As Boolean = False
    Property DenyAttachFile As Boolean
        Get
            Return _DenyAttachFile
        End Get
        Set(ByVal value As Boolean)
            If value Then
                Me.attachDatabaseRadioButton.Checked = False
                Me.selectDatabaseRadioButton.Checked = True
                Me.attachDatabaseRadioButton.Enabled = False
            Else
                Me.attachDatabaseRadioButton.Enabled = True
            End If
        End Set
    End Property

End Class
